"use strict";

var http = require("http");
var pathRegexp = require("./pathRegexp");
var url = require("url");

function App() {
    var self = this;
    this.route_get_handles = []; //get方法处理对象
    this.route_post_handles = []; //post方法处理对象

    //插件有序列表
    this.middleList = [];
    var tempMiddleList = this.middleList;

    //request事件响应函数
    function handle(req, res) {
        req.params = {};
        var middleIndex = 0; //插件索引
        var execMiddle = function () {
            var middle = tempMiddleList[middleIndex];
            if (middle) {
                middle(req, res, function () {
                    middleIndex += 1;
                    execMiddle();
                });
            } else {
                var handle = null;
                var path = url.parse(req.url).pathname; // /abc?age=12替换为 /abc
                //找到对应的路由器
                var findHandle = function (route_handles) {
                    for (var i = 0, len = route_handles.length; i < len; i++) {
                        var route_handle = route_handles[i];
                        var pass = route_handle.route.test(path);
                        if (pass) {
                            route_handle.route.paramNames.forEach(function (name, index){
                                var p1 = RegExp["$" + (index + 1)];
                                req.params[name] = RegExp["$" + (index + 1)];
                            });
                            handle = route_handle.handle;
                            break;
                        }
                    }
                };

                switch (req.method) {
                    case "GET":
                        findHandle(self.route_get_handles);
                        break;
                    case "POST":
                        findHandle(self.route_post_handles);
                        break;
                }
                if (handle) {
                    handle(req, res);
                } else {
                    res.statusCode = 404;
                    res.end();
                }
            }
        };
        execMiddle();
    }

    this.serverapp = http.createServer(handle);
}

//加入功能栈
App.prototype.use = function (middle) {
    this.middleList.push(middle);
};

//监听端口
App.prototype.listen = function () {
    this.serverapp.listen.apply(this.serverapp, arguments);
};

App.prototype.get = function (route, handle) {
    this.route_get_handles.push({route: pathRegexp(route), handle: handle});
};

App.prototype.post = function (route, handle) {
    this.route_post_handles.push({route: pathRegexp(route), handle: handle});
};


module.exports = App;